﻿using EFCore.BulkExtensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Pangeo.Admin.Interface.HrmDb;
using Pangeo.Admin.Models.FineReportDb.Entity;
using Pangeo.Admin.Services.FineReportDb;

namespace Pangeo.Admin.Tasks.Jobs
{
    public class PushWorkTimeToBI
    {
        private readonly IHrm hrmService;
        private readonly string fineReportDbConnStr;
        private readonly IServiceScopeFactory scopeFactory;

        public PushWorkTimeToBI(IServiceScopeFactory _scopeFactory)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                hrmService = scope.ServiceProvider.GetRequiredService<IHrm>();
                fineReportDbConnStr = scope.ServiceProvider.GetRequiredService<IConfiguration>().GetConnectionString("FineReportDb") ?? string.Empty;
            }

            scopeFactory = _scopeFactory;
        }

        /// <summary>
        /// 推送班次数据到BI
        /// </summary>
        public async Task<string> Run()
        {
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            var calcStartTime = DateTime.Parse(date + " 00:00:00");
            var calcEndTime = DateTime.Parse(date + " 23:59:59");
            var list = new List<HrmWorkTime>();

            try
            {
                var shiftDate = string.Empty;
                var workResult = await hrmService.CalcWorkResult(calcStartTime, calcEndTime);

                foreach (var item in workResult.WorkPeople)
                {
                    shiftDate = item.date.ToString("yyyy-MM-dd");
                    if (list.Any(t => t.EmpNo == item.people_no && t.ShiftDate == shiftDate))
                        continue;

                    list.Add(new HrmWorkTime()
                    {
                        EmpNo = item.people_no,
                        EmpName = item.people_name,
                        LedgerAccount = item.ledger_account,
                        PeopleCategory = item.people_category,
                        IsResearcher = item.is_researcher,
                        ShiftName = item.name,
                        ShiftStart = item.start,
                        ShiftEnd = item.end,
                        ShiftDate = shiftDate,
                        ClockIn = item.first_clock,
                        ClockOut = item.last_clock,
                        DeptCode = item.ou_code,
                        DeptName = item.ou_name,
                        UpdateTime = DateTime.Now
                    });
                }

                // 由于DbContext是有作用域生命周期的服务，也是通过Scope注册服务的，为了确保依赖注入（DI）容器中的服务按作用域（scope）进行管理，故每次任务执行时，创建一个新的作用域
                using (var scope = scopeFactory.CreateScope())
                {
                    var dbContext = scope.ServiceProvider.GetRequiredService<_FrDbContext>();

                    // 使用 dbContext 执行任务
                    await dbContext.BulkInsertOrUpdateAsync(list, options =>
                    {
                        // 使用EmpNo和ShiftTime作为匹配字段进行更新
                        options.UpdateByProperties = new List<string>() { nameof(HrmWorkTime.EmpNo), nameof(HrmWorkTime.ShiftDate) };

                        // 设置超时时间为 60 秒
                        options.BulkCopyTimeout = 60;
                    });
                }

                Console.WriteLine($"info: 已更新 {calcStartTime.ToString("yyyy-MM-dd HH:mm:ss")} ~ {calcEndTime.ToString("yyyy-MM-dd HH:mm:ss")} 排班数据{list.Count}条！");

                return string.Empty;
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
    }
}
